﻿using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;

namespace Mvc4Demo.Core
{
    public static class PdfConverter
    {
        public static MemoryStream HtmlToPdf(string htmlContents)
        {
            using (var document = new Document())
            {
                var memoryStream = new MemoryStream();
                var writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                var htmlContext = new HtmlPipelineContext(null);

                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                var pipeline = new CssResolverPipeline(cssResolver,
                                                       new HtmlPipeline(htmlContext,
                                                                        new PdfWriterPipeline(document, writer)));
                var worker = new XMLWorker(pipeline, true);
                var parser = new XMLParser(worker);
                parser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(htmlContents)));
                document.Close();
                return memoryStream;
            }
        }
    }
}